import torch

x = torch.arange(4.0)
x.requires_grad_(True)
y = 2 * torch.dot(x, x)
y.backward()
x.grad
# 输出： tensor([ 0.,  4.,  8., 12.])

x.grad.zero_()
y = x.sum()
y.backward()
x.grad
# 输出： tensor([1., 1., 1., 1.])

x.grad.zero_()
y = x * x
# 等价于y.backward(torch.ones(len(x)))
y.sum().backward()
x.grad